use std::fs;
use serde::{Deserialize, Serialize};
use crate::config::Environment;

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AppConfig {
    pub app_env: String,
    pub api_url: String,
    pub timeout: i32,

    pub sign_config:SignConfig,
    pub login_config:LoginConfig,
    pub login_bind:LoginBind,
}

#[derive(Debug, Clone,Default, Serialize, Deserialize)]
pub struct LoginConfig{
    #[serde(rename = "tokenKey")]
    pub token_key:String,
    #[serde(rename = "runameKey")]
    pub runame_key:String,
    #[serde(rename = "rpwdKey")]
    pub rpwd_key:String,
    #[serde(rename = "rmeKey")]
    pub rme_key:String,
}

#[derive(Debug, Clone,Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SignConfig{
    pub verify_sign:i32,
    pub sign_salt:String,
    pub sign_header:String,
    pub random_start:i32,
    pub random_end:i32,
}

#[derive(Debug, Clone,Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct LoginBind{
    pub login_bind:i32,
    pub login_bind_salt:String,
    pub login_bind_header:String,
}

impl Default for AppConfig {
    fn default() -> Self {
        Self {
            app_env: "development".into(),
            api_url: "http://localhost:8280".into(),
            timeout: 30,

            sign_config:SignConfig{
                verify_sign:0,
                sign_salt:"Byws3q6z3twIBIVu".into(),
                sign_header:"pxfy".into(),
                random_start:214536,
                random_end:314536,
            },

            login_config:LoginConfig{
                token_key:"Admin-Token".into(),
                runame_key:"userName".into(),
                rpwd_key:"password".into(),
                rme_key:"rberme".into(),
            },

            login_bind:LoginBind{
                login_bind:0,
                login_bind_salt:"fqjClgGyyMXowHx5".into(),
                login_bind_header:"iykw".into(),
            },
        }
    }
}

// 可选: 从 JSON 文件加载配置（替代方案）
#[allow(dead_code)]
fn load_from_json() -> AppConfig {
    let env = Environment::detect();
    let file_path = match env {
        Environment::Development => "config/development.json",
        Environment::Production => "config/production.json",
    };

    match fs::read_to_string(file_path) {
        Ok(content) => {
            serde_json::from_str(&content).unwrap_or_else(|e| {
                log::error!("解析 JSON 配置失败: {}", e);
                Default::default()
            })
        }
        Err(e) => {
            log::error!("读取配置文件失败: {}", e);
            Default::default()
        }
    }
}